package com.ltmonitor.web.controller.command;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.AlarmRecord;
import com.ltmonitor.entity.TerminalCommand;
import com.ltmonitor.service.JT808Constants;
import com.ltmonitor.web.util.JsonMessage;

/**
 * 调度文本信息下发
 * 
 * @author DELL
 * 
 */
@Controller
@RequestMapping("/sendText")
public class SendTextAction extends TerminalCommandAction {
		

	@RequestMapping("/view.action")
	public String view(long vehicleId, @RequestParam(defaultValue="0") long alarmId, Model m) {
		m.addAttribute("vehicleId", vehicleId);
		m.addAttribute("alarmId", alarmId);
		
		return "/command/sendText";
	}
	
	@RequestMapping("/getView.action")
	public String getView(Model model) {
		model.addAttribute("message", "加载成功");
		return "/command/sendTextNew";
	}

	/**
	 * 
	 * @param vehicleId
	 * @param textContent
	 * @param displayOption 文本信息设置类型 0 1：紧急 1 保留 2 1：终端显示器显示 3 1：终端TTS播读 4 1：广告屏显示 5～7 保留
	 * @param allSelectedVehicle 是否对用户所选择的车辆进行批量设置命令，on 代表是
	 * @param alarmId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/send.action")
 public JsonMessage execute(int vehicleId,String textContent , String[] displayOption, String allSelectedVehicle, @RequestParam(defaultValue="0") long alarmId) {

		try {
			if (displayOption == null || displayOption.length == 0) {
				return json(false, "请选择文本显示类型!");
			}
			TerminalCommand tc = new TerminalCommand();
			tc.setCmdType(JT808Constants.CMD_SEND_TEXT);
			int[] bitValues = new int[8];
			String strDisplay = "";
			for (String op : displayOption) {
				int index = Integer.parseInt(op);
				bitValues[index] = 1;

				if (index == 0)
					strDisplay += "紧急,";
				else if (index == 2)
					strDisplay += "终端显示器显示,";
				else if (index == 3)
					strDisplay += "终端TTS播读,";
				else if (index == 4)
					strDisplay += "广告牌显示,";
				else if (index == 5)
					strDisplay += "弗斯特广告屏,";
			}

			// 0x80”不用标准的。"0xc0"
			strDisplay = strDisplay.substring(0, strDisplay.length() - 1);

			StringBuilder strBit = new StringBuilder();
			ArrayUtils.reverse(bitValues);
			for (int bit : bitValues)
				strBit.append(bit);
			byte bitValue = Byte.valueOf(strBit.toString(), 2); // 将位数组转换为字节值

			if (bitValues[2] == 1) {
				bitValue = (byte) 0x80;
			}
			tc.setCmd("" + bitValue);
			String cmdData = bitValue + ";" + textContent;
			
			if ("on".equals(allSelectedVehicle)) {
				String REGISTER_KEY = "registerVehicleIds";
				List<Long> vehicleIdList = (List<Long>) super.getFromSession(
						REGISTER_KEY);
				if (vehicleIdList != null && vehicleIdList.size() >= 1) {
					TerminalCommand command = new TerminalCommand();
					command.setVehicleId(vehicleId);
					command.setCmdData(cmdData);
					command.setCmd("" + bitValue);
					command.setCmdType(JT808Constants.CMD_SEND_TEXT);
					for (long vId : vehicleIdList) {
						if (vId != vehicleId)
							SendCommand(command,vId);
					}
				}
			}
			tc.setCmdData(bitValue + ";" + textContent);
			tc.setVehicleId(vehicleId);
			tc.setRemark(strDisplay);
			SendCommand(tc);

			if (alarmId > 0)
				this.processAlarm(alarmId, AlarmRecord.PROCESS_SEND_TEXT,"文本:"+textContent);

			return json(true, tc.getEntityId());
		} catch (Exception ex) {
			return json(false, ex.getMessage());
		}
	}

	
	
	
	/**
	 * author:shinion
	 * date:2018-12-26
	 * 
	 * 发送文本到多个车辆，并且每个车辆和报警不是一一对应，
	 * 发送和处理分开进行，对不同的车辆发送文本，对所有的报警记录进行统一处理
	 * @param vehicleIds 车辆列表
	 * @param textContent 发送文本
	 * @param displayOption 文本信息设置类型 0 1：紧急 1 保留 2 1：终端显示器显示 3 1：终端TTS播读 4 1：广告屏显示 5～7 保留
	 * @param alarmIds adas 报警列表
	 * @return
	 * long[] vehicleIds,String textContent,String[] displayOption,long[] adasAlarmIds
	 */
	@ResponseBody
	@RequestMapping("/sendAdasAlarms.action")
	public JsonMessage sendAdasAlarms(long[] vehicleIds,String textContent,String[] displayOption,long[] adasAlarmIds,long[] alarmIds) {
		try {		
			List idList = sendCommand(vehicleIds,textContent,displayOption);
			/*
			 *处理多条报警数据 
			 */
			if(alarmIds.length>0 && adasAlarmIds.length > 0)
			{
				this.processAdasAlarms(idList,alarmIds,adasAlarmIds, AlarmRecord.PROCESS_SEND_TEXT,"文本:"+textContent);
			}
			
			//返回数据
			return json(true, idList);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return json(false, e.getMessage());
		}
		
	}



/**
 * author:shinion
 * date:2018-12-27
 * 
 * 发送文本到多个车辆，发送包括主动安全和非主动安全的所有报警信息，并且主动安全报警信息只有alarm表中的索引
 * 首先进行命令发送，然后更新数据库
 * @param vehicleIds 车辆id
 * @param textContent 显示文本
 * @param displayOption 显示类型
 *  @param alarmIdsForAdas  主动安全的id索引，为alarm表中的索引
 * @param alarmIds 非主动安全报警的id索引
 * @return
 */
@ResponseBody
@RequestMapping("/sendAlarms.action")
  public JsonMessage sendAalrms(long[] vehicleIds,String textContent,String[] displayOption,long[] alarmIds,long[] alarmIdsForAdas) {
	try {		
		
		/*
		 *1.发送命令
		 *2.更新非主动安全报警信息
		 *3.更新主动安全报警信息
		 *			3.1.通过alarm表中的id获取index，
		 *			3.2更新所有没有处理过的记录的处理状态信息
		 *			3.3.更新alarm表中的处理数量等于报警总数
		 *			3.4发送809指令
		 */
		List idList = sendCommand(vehicleIds,textContent,displayOption);
		
		/*
		 *处理多条报警数据 
		 */
		if(alarmIds.length>0)
		{
			//批量更新报警记录信息
			for(long alarmId:alarmIds) {
				this.processAlarm(alarmId, AlarmRecord.PROCESS_SEND_TEXT,"文本:"+textContent);
			}

		}
		
		//批量处理主动安全报警记录
		if(alarmIdsForAdas.length >0) {
			this.processAdasAlarmByAlarmIds(idList,alarmIdsForAdas,AlarmRecord.PROCESS_SEND_TEXT,"文本:"+textContent);
		}
		
		//返回数据
		return json(true, idList);
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
		return json(false, e.getMessage());
	}
  }


/**
 * author:shinion
 * date:2018-12-27
 * 发送命令方法
 * @param vehicleIds 车辆id列表
 * @param textContent 发送内容
 * @param displayOption 显示类型
 * @return
 */
 private List sendCommand(long[] vehicleIds,String textContent,String[] displayOption) {
		List result = new ArrayList();// 定义返回列表
		try {
			// 定义终端命令
			TerminalCommand tc = new TerminalCommand();
			tc.setCmdType(JT808Constants.CMD_SEND_TEXT);
			int[] bitValues = new int[8];
			String strDisplay = "";
			for (String op : displayOption) {
				int index = Integer.parseInt(op);
				bitValues[index] = 1;

				if (index == 0)
					strDisplay += "紧急,";
				else if (index == 2)
					strDisplay += "终端显示器显示,";
				else if (index == 3)
					strDisplay += "终端TTS播读,";
				else if (index == 4)
					strDisplay += "广告牌显示,";
				else if (index == 5)
					strDisplay += "弗斯特广告屏,";
			}

			// 0x80”不用标准的。"0xc0"
			strDisplay = strDisplay.substring(0, strDisplay.length() - 1);

			StringBuilder strBit = new StringBuilder();
			ArrayUtils.reverse(bitValues);
			for (int bit : bitValues)
				strBit.append(bit);
			byte bitValue = Byte.valueOf(strBit.toString(), 2); // 将位数组转换为字节值

			if (bitValues[2] == 1) {
				bitValue = (byte) 0x80;
			}
//			tc.setCmd("" + bitValue);
			String cmdData = bitValue + ";" + textContent;

			// 发送内容
			// 定义命令
			TerminalCommand command = new TerminalCommand();
			command.setCmdData(cmdData);
			command.setCmd("" + bitValue);
			command.setCmdType(JT808Constants.CMD_SEND_TEXT);
			for (long vid : vehicleIds) {
				SendCommand(command, vid);// 发送文本命令
				result.add(""+command.getEntityId());// 存放指令id
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return result;
	}
}
